<template>
  <view class="confirmbody confirmPage">
    <nut-form :model-value="formData" ref="ruleForm">
      <!-- 承运单号&目的地&库位 -->
      <view class="conCard">
        <nut-form-item label="承运单号" required prop="billNo">
          <nut-input :border="false" v-model="formData.billNo" placeholder="请输入9位数" type="digit">
            <template v-slot:right>
              <Scan />
            </template>
          </nut-input>
        </nut-form-item>

        <!-- 选择目的地 -->
        <view @click="showBranchTree = true">
          <nut-form-item class="flex-ld" label="到达地" required prop="destinationAddress">
            <nut-input readonly :border="false" v-model="formData.destinationBranchName" placeholder="请选择到达地"></nut-input>
            <IconFont name="rect-right"></IconFont>
          </nut-form-item>
        </view>

        <!-- 货号 起运地（公司简称）+目的地（公司简称）+运单编号 - 件数-->
        <view>
          <nut-form-item class="flex-ld" label="货号" required prop="locationName">
            {{ formData.startBranchShortName }}{{ formData.destinationBranchShortName }}{{ formData.billNo }}-{{ totalGoods }}
          </nut-form-item>
        </view>

        <!-- 选择库位 -->
        <view @click="showWareHouse = true">
          <nut-form-item class="flex-ld" label="库位" required prop="locationName">
            <nut-input readonly :border="false" v-model="formData.locationName" placeholder="请选择库位"></nut-input>
            <IconFont name="rect-right"></IconFont>
          </nut-form-item>
        </view>
      </view>
      <!-- 收发货人信息&身份证号 -->
      <view class="conCard">
        <nut-cell @click="openAddressBook(1)">
          <div class="flex">
            <image src="../../assets/images/index/我要发货/shouye_icon_fahuo.png" style="width: 42px; height: 42px" />
            <view>
              <view>{{ formData.shipper || '请输入发货人姓名' }}{{ formData.shipperMobile || '请输入发货人手机号' }}</view>
              <view>{{ formData.shipperAdd || '请输入发货人地址' }}</view>
            </view>
          </div>
        </nut-cell>
        <nut-cell @click="openAddressBook(2)">
          <div class="flex">
            <image src="../../assets/images/index/我要发货/shouye_icon_shouhuo.png" style="width: 42px; height: 42px" />
            <view>
              <view>{{ formData.receiver || '请输入收货人姓名' }}{{ formData.receiverMobile || '请输入收货人手机号' }}</view>
              <view>{{ formData.receiverAdd || '请输入收货人地址' }}</view>
            </view>
          </div>
        </nut-cell>
        <nut-form-item label="身份证号" required prop="shipperId">
          <nut-input :border="false" v-model="formData.shipperId" placeholder="请输入身份证号"></nut-input>
        </nut-form-item>
      </view>
      <!-- 基本信息&其他信息 -->
      <view class="conCard">
        <nut-tabs v-model="tabValue">
          <nut-tab-pane title="基本信息" pane-key="0">
            <view class="tabCon">
              <!-- 货物信息 start -->
              <nut-form-item label="货物信息" required prop="customerName">
                <div class="flex-end">
                  <nut-button color="#0966FF" size="mini" @click="toGoodsPage">添加货物</nut-button>
                </div>
              </nut-form-item>
              <nut-cell-group>
                <nut-cell class="flex-ld grayBg" v-for="(item, index) in goodsInfo" :key="index">
                  <span>{{ item.goodsName }}{{ item.goodsNumber }}件,{{ item.weigh }}Kg,{{ item.goodsVolume }}m³,{{ item.packing }}</span>
                  <p class="flex-ld"><span class="fontBlue" @click="editGoods(item, index)">编辑</span><span class="fontRed" @click="delGoods(item, index)">删除</span></p>
                </nut-cell>
              </nut-cell-group>

              <!-- 付款方式 现付 提付 签单 start -->
              <nut-form-item class="flex-ld" label="付款方式" prop="clearingForm">
                <nut-radio-group v-model="formData.clearingForm" direction="horizontal">
                  <nut-radio label="1">现付</nut-radio>
                  <nut-radio label="2">提付</nut-radio>
                  <nut-radio label="3">签单</nut-radio>
                </nut-radio-group>
              </nut-form-item>

              <!-- 签单单位 -->
              <nut-form-item v-if="formData.clearingForm == '3'" class="flex-ld grayBg" label="签单单位" required prop="">
                <nut-input class="grayInput" readonly :border="false" v-model="formData.customerName" @click="showSignUnit = true" placeholder="请选择签单单位"></nut-input>
                <IconFont name="rect-right"></IconFont>
              </nut-form-item>

              <!-- 接货方式 start -->
              <nut-form-item class="flex-ld" label="接货方式" prop="isReceiving">
                <nut-radio-group v-model="formData.isReceiving" direction="horizontal">
                  <nut-radio label="0">无需接货</nut-radio>
                  <nut-radio label="1">上门接货</nut-radio>
                </nut-radio-group>
              </nut-form-item>
              <view v-if="formData.isReceiving == '1'">
                <nut-form-item label="接货时间" class="grayBg initInput" required></nut-form-item>
                <nut-form-item class="flex-ld grayBg" label="" prop="receiveStartTimeStr">
                  <span style="width: 200rpx">开始时间：</span>
                  <nut-input class="grayInput" readonly :border="false" v-model="receiveStartTimeStr" @click="openTimeModel(0)" placeholder="接货开始时间"></nut-input>
                  <IconFont name="rect-right"></IconFont>
                </nut-form-item>
                <nut-form-item class="flex-ld grayBg" label="" prop="receiveEndTimeStr">
                  <span style="width: 200rpx">结束时间：</span>
                  <nut-input class="grayInput" readonly :border="false" v-model="receiveEndTimeStr" @click="openTimeModel(1)" placeholder="接货结束时间"></nut-input>
                  <IconFont name="rect-right"></IconFont>
                </nut-form-item>

                <nut-form-item class="flex-end grayBg" label="大小车" required prop="bigOrSmall">
                  <nut-radio-group v-model="formData.bigOrSmall" direction="horizontal">
                    <nut-radio label="2">小车</nut-radio>
                    <nut-radio label="1">大车</nut-radio>
                  </nut-radio-group>
                </nut-form-item>
                <nut-form-item class="flex-end grayBg" label="接货费" required prop="takeFee">
                  <nut-input :border="false" readonly v-model="formData.takeFee" placeholder="请输入交接货费金额"></nut-input>元
                </nut-form-item>
              </view>

              <!-- 提货方式 start -->
              <nut-form-item label="提货方式" class="initInput">
                <span @click="showDeliver = true">{{ deliverString }}</span>
                <IconFont name="rect-right"></IconFont>
              </nut-form-item>
              <!-- 提货方式 end -->
              <nut-form-item label="承运类型" class="initInput">
                <span @click="showSendType = true">{{ getSendTypeStr(formData.sendType) }} {{ getUrgentStr(formData.urgent) }}</span>
                <IconFont name="rect-right"></IconFont>
              </nut-form-item>

              <nut-form-item label="保价" class="initInput">
                <span @click="showInsure = true">{{ insureString }}</span>
                <IconFont name="rect-right"></IconFont>
              </nut-form-item>

              <nut-form-item label="代收货款" v-if="collectionPayment" class="initInput">
                <!-- <nut-input readonly :border="false" v-model="collectionString" placeholder="点击选择代收方式"></nut-input> -->
                <span @click="showPayment = true">{{ paymentStr || '请选择代收货款方式' }}</span>
                <IconFont name="rect-right"></IconFont>
              </nut-form-item>
            </view>
          </nut-tab-pane>
          <nut-tab-pane title="其他信息" pane-key="1">
            <view class="tabCon otherBox">
              <nut-form-item class="flex-ld" label="长途运费" prop="longPrice">
                <nut-input class="grayInput" :border="false" v-model="formData.longPrice" placeholder="请输入长途运费"></nut-input><span class="span">元</span>
              </nut-form-item>
              <nut-form-item class="flex-ld" label="送货费" prop="shf" v-if="formData.pickUpMode == '2'">
                <nut-input class="grayInput" readonly :border="false" v-model="sendPrice" placeholder="送货费"></nut-input> <span class="span">元</span>
              </nut-form-item>
              <nut-form-item label="起运地其他费用" class="">
                <span @click="showOtherStart = true" class="textRight">{{ feeStartStr }}</span>
                <IconFont name="rect-right"></IconFont>
              </nut-form-item>
              <nut-form-item label="目的地其他费用" class="">
                <span @click="showOtherEnd = true" class="textRight">{{ feeEndStr }}</span>
                <IconFont name="rect-right"></IconFont>
              </nut-form-item>
              <nut-form-item class="flex-ld" label="装车类型" prop="loadType">
                <nut-radio-group v-model="formData.loadType" direction="horizontal">
                  <nut-radio label="1">内配</nut-radio>
                  <nut-radio label="2">外装</nut-radio>
                </nut-radio-group>
              </nut-form-item>
              <nut-form-item class="flex-ld" label="短途配载" prop="shortLoad">
                <nut-radio-group v-model="formData.shortLoad" direction="horizontal">
                  <nut-radio label="1">是</nut-radio>
                  <nut-radio label="0">否</nut-radio>
                </nut-radio-group>
              </nut-form-item>
              <nut-form-item class="flex-ld" label="内部运单" prop="reservedBill">
                <nut-radio-group v-model="formData.reservedBill" direction="horizontal">
                  <nut-radio label="1">是</nut-radio>
                  <nut-radio label="0">否</nut-radio>
                </nut-radio-group>
              </nut-form-item>
              <nut-form-item class="flex-ld" label="信息设备" prop="infoDevice">
                <nut-radio-group v-model="formData.infoDevice" direction="horizontal">
                  <nut-radio label="1">是</nut-radio>
                  <nut-radio label="0">否</nut-radio>
                </nut-radio-group>
              </nut-form-item>
              <!-- 信息设备-收货人 -->
              <nut-form-item v-if="formData.infoDevice == '1'" class="flex-ld receivePeople" label="收货人" required prop="receivePeopleStr">
                <nut-input readonly :border="false" v-model="receivePeopleStr" @click="showPeople = true" placeholder="请选择收货人"></nut-input>
              </nut-form-item>
              <!-- 回单类型  -->
              <nut-form-item label="回单类型" class="">
                <span @click="billServerModel = true" class="textRight">{{ billServerStr }}</span>
                <IconFont name="rect-right"></IconFont>
              </nut-form-item>
              <!-- 开单员 -->
              <nut-form-item label="开单员" class="">
                <span @click="openBillModel(1)" class="textRight">{{ formData.biller || '请选择开单员' }}</span>
                <IconFont name="rect-right"></IconFont>
              </nut-form-item>
              <!-- 接单员  -->
              <nut-form-item label="接单员" class="">
                <span @click="openBillModel(0)" class="textRight">{{ formData.taker || '请选择接单员' }} </span>
                <IconFont name="rect-right"></IconFont>
              </nut-form-item>
              <!-- 厂单日期 -->
              <nut-form-item label="厂单日期" class="">
                <span @click="showFactory = true" class="textRight">{{ formData.factoryDate || '请选择厂单日期' }} </span>
                <IconFont name="rect-right"></IconFont>
              </nut-form-item>
            </view>
          </nut-tab-pane>
        </nut-tabs>
      </view>
    </nut-form>

    <!-- 费用明细 -->

    <!-- 地址抽屉 -->
    <AddressForm @receiveAddressForm="closeAddressForm" :formType="formType" :addressBookInit="addressBookInit" :showRound="showAddressForm" />

    <!-- 库位抽屉 -->
    <WareHouse @sendWareHouseMsg="closeWareHouse" :showRound="showWareHouse" />

    <!-- 签单单位抽屉 -->
    <SignUnitModel @sendSignUnitMsg="closeSignUnitModel" :showRound="showSignUnit" />

    <!-- 接货时间抽屉 -->
    <ReceiveTimeModel @sendReceiveTimeMsg="closeReceiveTimeModel" :showRound="showReceiveTime" :timeType="timeType" :startTime="receiveStartTimeStr" :endTime="receiveEndTimeStr" />

    <!-- 提货方式抽屉 -->
    <DeliveryModel
      @sendDeliverMsg="closeDelivereModel"
      :showRound="showDeliver"
      :destinationAddress="formData.destinationAddress"
      :destinationBranch="formData.destinationBranch"
      :deliveryTime="formData.deliveryTime"
      :pickUpMode="formData.pickUpMode"
      :deliveryType="formData.deliveryType"
      :subsidyType="formData.subsidyType"
      :dischargeCargo="formData.dischargeCargo"
      :dischargeElevator="formData.dischargeElevator"
      :elevatorNum="formData.elevatorNum"
      :dischargeServer="formData.dischargeServer"
      :initUrgent="formData.urgent"
      :initLimitSend="formData.limitSend"
    />

    <!-- 承运类型抽屉 -->
    <SendTypeModel @sendSendTypeMsg="closeSendTypeModel" :initSendType="formData.sendType" :showRound="showSendType" />

    <!-- 保价抽屉 -->
    <InsureModel @sendInsureMsg="closeInsureModel" :showRound="showInsure" />

    <!-- 代收货款抽屉 -->
    <PaymentModel @sendPaymentMsg="closePaymentModel" :showRound="showPayment" :phone="formData.shipperMobile" />

    <!-- 到达地选点抽屉 -->
    <BranchTreeModel @sendTreeMsg="closeBranchModel" :showRound="showBranchTree" />

    <!-- 起运地费用抽屉 -->
    <FeeStartModel @sendFeeStartMsg="closeFeeStartModel" :showRound="showOtherStart" :costList="feeStartSimple" />

    <!-- 目的地费用抽屉 -->
    <FeeEndModel @sendFeeEndMsg="closeFeeEndModel" :showRound="showOtherEnd" :costList="feeEndSimple" />

    <!-- 设备信息收货人抽屉 -->
    <PeopleModel @sendReceivePeopleMsg="closePeopleModel" :showRound="showPeople" />

    <!-- 接/开单员抽屉 -->
    <BillPeopleModel @sendBillPeopleMsg="closeBillPeopleModel" :showRound="showBillPeople" :billType="billType" />

    <!-- 厂单日期抽屉 -->
    <FactoryDateModel @sendFactoyMsg="closeFactoryModel" :factoryDate="formData.factoryDate" :showRound="showFactory" />

    <!-- 回单类型抽屉 -->
    <nut-popup class="billServerBox" position="bottom" closeable round :style="{ height: '50%' }" @click-close-icon="confirmBillServer(0)" v-model:visible="billServerModel">
      <nut-cell style="color: #252525; font-weight: bold" title="回单类型aaa"></nut-cell>
      <nut-checkbox-group v-model="billServerGroup" :max="2">
        <nut-cell> <nut-checkbox label="1"> 附单据，资料 </nut-checkbox></nut-cell>
        <nut-cell> <nut-checkbox label="2"> 承运单 </nut-checkbox></nut-cell>
        <nut-cell> <nut-checkbox label="3"> 附厂单，资料 </nut-checkbox></nut-cell>
      </nut-checkbox-group>
      <nut-cell class="inputBox flex-ld">
        <span>签</span>
        <nut-input class="input" placeholder="" v-model="formData.billNum" />
        <span>联</span>
      </nut-cell>
      <nut-button class="btn" block type="primary" color="#0966ff" @click="confirmBillServer(1)">确定</nut-button>
    </nut-popup>

    <!-- 费用明细 -->
    <nut-popup position="bottom" closeable round @click-close-icon="totalPriceModel = false" v-model:visible="totalPriceModel">
      <nut-cell style="color: #252525; font-weight: bold" title="费用明细"></nut-cell>
      <view class="feeBox">
        <view
          ><span class="totalTitle">合计费用</span><span class="totalPrice">￥{{ totalPriceNumber.toFixed(2) }}</span></view
        >
        <view class="feeLine" v-for="(item, index) in totalPrice" :key="index">
          <span v-if="Number(item.actualMoney) !== 0">{{ item.ssopRemart }}</span>
          <span v-if="Number(item.actualMoney) !== 0">￥{{ item.actualMoney }} 元</span>
        </view>
      </view>
      <nut-cell class="submitBox">
        <p class="totalFont">
          <span>合计</span><span class="blueFont">￥{{ totalPriceNumber.toFixed(2) }}</span
          ><span>明细^</span>
        </p>
        <nut-button type="primary" size="small" style="margin-right: 10px" class="submit" @click="submit">确认订单</nut-button>
      </nut-cell>
    </nut-popup>

    <view class="submitBox">
      <p class="totalFont" @click="totalPriceModel = true">
        <span>合计</span><span class="blueFont">￥{{ totalPriceNumber.toFixed(2) }}</span
        ><span>明细^</span>
      </p>
      <nut-button type="primary" size="small" style="margin-right: 10px" class="submit" @click="submit">确认订单</nut-button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { onMounted, ref, reactive, computed, watch } from 'vue'
import Taro, { useReady, useRouter, useDidShow } from '@tarojs/taro'
import { IconFont } from '@nutui/icons-vue-taro'
import dayjs from 'dayjs'
import useOrderStore from '@/store/order'
import { getList, getTakeFee, getLongPriceFee, getSendGoodsFee, getPaymentToggle } from '@/@api/wait' // wait的接口
import { data } from './data.js' // wait的接口

import useConfirmStore from '@/store/confirm'
const confirmStore = useConfirmStore()

const datas = data

import Scan from '@/components/Scan/index.vue' // 扫码组件
// import sendForm from "@/components/sendForm/index.vue"; // 地址抽屉组件
import AddressForm from './addressForm.vue' // 地址抽屉组件
import WareHouse from './wareHouse.vue' // 库位抽屉组件
import SignUnitModel from './signUnitModel.vue' // 签单单位抽屉组件
import ReceiveTimeModel from './receiveTimeModel.vue' // 接货时间抽屉组件
import SendTypeModel from './sendTypeModel.vue' // 承运类型抽屉组件
import InsureModel from './insureModel.vue' // 保价抽屉组件
import PaymentModel from './paymentModel.vue' // 代收货款抽屉组件
import DeliveryModel from './deliveryModel.vue' // 提货方式抽屉组件
import BranchTreeModel from './branchTree.vue' // 到达地选点抽屉组件
import FeeStartModel from './feeStartModel.vue' // 起运地费用抽屉组件
import FeeEndModel from './feeEndModel.vue' // 目的地费用抽屉组件
import PeopleModel from './receivePeopleModel.vue' // 信息设备收货人抽屉组件
import FactoryDateModel from './factoryDateModel.vue' // 厂单日期抽屉组件
import BillPeopleModel from './billPeopleModel.vue' // 接开单员抽屉组件

useReady(() => {
  Taro.setNavigationBarTitle({
    title: '确认订单'
  })
})

useDidShow(() => {})

const router = useRouter()

const orderStore = useOrderStore() // 用于获取ssoId

// 表单数据
const formData = reactive<any>({
  // card1
  billNo: '', // 运单编号
  startBranchShortName: '', // 起运地 公司简称
  destinationAddress: '', // 目的地
  destinationBranch: '', // 到达地网点编号 推荐网点编号 目的地网点编号
  destinationBranchName: '', // 到达地名称
  destinationBranchShortName: '', // 目的地 公司简称
  locationName: '', // 库位
  // card2
  shipper: '', // 发货人
  shipperMobile: '', // 发货人手机号
  shipperAdd: '', // 发货人地址
  receiver: '', // 收货人
  receiverMobile: '', // 收货人手机号
  receiverAdd: '', // 收货人地址
  // card3
  shipperId: '', // 身份证号
  // card4
  clearingForm: '', // 付款方式
  contractedNo: '', //签单单位的id
  customerName: '', //签单单位的名称
  toFromAdd: '', // 计算接货费
  startAddress: '', // 计算接货费
  // card5
  isReceiving: '', // 是否接货 0 1
  receivingTime: '', // 接货时间
  bigOrSmall: '1', // 大小车  1大车 2小车
  takeFee: '', // 接货费
  // card6
  deliveryTime: '', // 配送时间
  pickUpMode: '', // 提货方式
  deliveryType: '', // 送货类型
  subsidyType: '', // 送货补贴
  dischargeServer: '', // 卸货服务
  dischargeCargo: '', // 是否卸货
  dischargeElevator: '', // 是否电梯
  elevatorNum: '', // 卸货上几楼
  bonusFee: '', // 送货补贴费用
  urgent: null, // 0不加急 1加急
  limitSend: null, // 是否限时送
  goodT: {}, // 货物类型
  largeCargo: null, // 是否大件货物
  exhibitionGoods: null, // 是否展会货物
  specialGoods: null, // 特殊货物
  fillingCargo: null, // 填仓货物
  holidaySurCharge: null, // 特殊节假日货物

  // card7 承运类型
  sendType: '', // 1快件、2、普件、3整车、4 506经济件、5 506商务件、6次日达、7隔日达
  // card8 保价
  insuredFee: 0, // 保费
  insuredMoney: null, // 声明价值
  insuredPrice: null, // 是否保价
  insuredRate: null, // 费率

  // card9 待收货款
  accountName: '', // 户名
  bankName: '', // 开户行

  // 其它信息
  longPrice: '', // 长途运费

  // 起运地其它费用
  // 目的地其它费用
  loadType: '1', // 装车类型 1内配 2外装
  shortLoad: '0', // 短途配载  0-否 1-是
  reservedBill: '0', // 内部运单  0-否 1-是
  infoDevice: '1', // 信息设备
  billServer: '1', // 单据服务  1、附单据，材料 2、承运单 3、附厂单、资料 逗号隔开
  billNum: '', // 单据联页
  biller: '', // 开单员
  taker: '', // 接单员
  factoryDate: '', // 厂单日期

  // 其他要存的数据
  costList: [] // 费用
})

const sendPrice = ref(0) // 送货费 计算出来的 前端存
const totalPriceNumber = ref(0) // 总费用明细
const totalPriceModel = ref(false) // 费用明细抽屉
const totalPrice = computed(() => {
  let totalPrice = [
    {
      ssopRemart: '长途运费',
      actualMoney: formData.longPrice || 0
    },
    {
      ssopRemart: '送货费',
      actualMoney: sendPrice.value || 0
    },
    {
      ssopRemart: '接货费',
      actualMoney: formData.takeFee || 0
    },
    {
      ssopRemart: '保价费',
      actualMoney: formData.insuredFee || 0
    },
    // 开始
    {
      ssopRemart: '服务费',
      actualMoney: formData.insuredFee || 0
    },
    {
      ssopRemart: '附单据费用',
      actualMoney: formData.insuredFee || 0
    },
    {
      ssopRemart: '目的地带搬运卸货费',
      actualMoney: formData.insuredFee || 0
    },
    {
      ssopRemart: '二次送货补贴',
      actualMoney: formData.insuredFee || 0
    },
    {
      ssopRemart: '补签单费用',
      actualMoney: formData.insuredFee || 0
    },
    {
      ssopRemart: '调增送货费',
      actualMoney: formData.insuredFee || 0
    },
    {
      ssopRemart: '其他/营销部奖金',
      actualMoney: formData.insuredFee || 0
    },
    {
      ssopRemart: '代收中转费',
      actualMoney: formData.insuredFee || 0
    },
    {
      ssopRemart: '工本费',
      actualMoney: formData.insuredFee || 0
    }
  ]
  // 计算费用
  totalPriceNumber.value = totalPrice.reduce((accumulator, item) => {
    return accumulator + Number(item.actualMoney)
  }, 0)

  return totalPrice
})

const costListSimple = ref([])
const feeStartSimple = ref<any>([]) // 最后计算用这个
const feeEndSimple = ref<any>([]) // 最后计算用这个

// 货物信息参数
const goodsInfo = ref<any>([])
const goodsSum = ref(0) // 货物总件数

const showBranchTree = ref(false) // 到达地选点抽屉

const showWareHouse = ref(false) // 库位抽屉组件的显隐

const showAddressForm = ref(false) // 地址簿抽屉组件的显隐
const formType = ref('发货人')
const addressBookInit = ref() // 默认数据

const tabValue = ref('0') // tab切换选项卡

const takeFeeVolume = ref(0)
const takeFeeWeight = ref(0)
const totalGoods = ref(0) // 总货物件数
const showReceiveTime = ref(false) // 接货时间弹窗
const timeType = ref() // 开始 0 结束 1

const showSendType = ref(false) // 承运类型抽屉

const showInsure = ref(false) // 保价抽屉
const insureString = ref('不保价')

const collectionPayment = ref(true) // 是否代收货款
const showPayment = ref(false) // 代收货款弹窗
const paymentStr = ref('') // 代收货款回显文本

const showDeliver = ref(false) // 提货方式抽屉显隐
const deliverString = ref('请选择提货方式')

// 计算送货费 发生改变而改变
const baiduDistance = ref(0) // 推荐网点数据计算送货费
const baiduDistanceNo = ref(0) // 推荐网点数据计算送货费不带公里数
const isNormal = ref() // 推荐网点returnForm返回的isNormal

const showOtherStart = ref(false) // 起运地其他费用抽屉
const showOtherEnd = ref(false) // 目的地其他费用抽屉

const showPeople = ref(false)
const receivePeopleStr = ref('')

const showSignUnit = ref(false) // 签单单位弹窗
const billInfo = ref() // 签单单位回单详情
const billServerGroup = ref() // 选中的回单类型数组
const billServerModel = ref(true) // 回单类型弹窗
const billFee = ref(0) // 附单据费用 累加 存到costList里

const showBillPeople = ref(false) // 接开单员抽屉
const billType = ref() // 接开单类型 1开单员 0接单员

const showFactory = ref(false) // 厂单日期抽屉

onMounted(() => {
  Taro.authorize({
    scope: 'scope.userLocation',
    success() {
      console.log('获取权限成功')
    },
    fail() {
      console.log('获取权限失败')
    }
  })

  if (router?.params.goods) {
    // 1.取出store的formData数据渲染到表单上
    Object.assign(formData, confirmStore.order.formData)
    // 2.取出store的goodsInfo渲染到页面
    goodsInfo.value = confirmStore.order.goodsInfo
    // console.log(confirmStore.order.goodsInfo, '仓库里的货物信息数组', goodsInfo.value, '赋值仓库里的货物信息')
    // 3.找到edit为true的修改那条货物信息
    const goods = JSON.parse(router.params.goods)
    // 4.判断是新增还是修改
    // if (goods.tool == 'edit') {
    //   console.log('修改数据')
    goodsInfo.value.forEach((item) => {
      if (item.edit == true) {
        item.goodsName = goods.goodsName
        item.goodsType = goods.goodsType
        item.goodsNumber = goods.goodsNumber
        item.weigh = goods.weigh
        item.goodsVolume = goods.goodsVolume
        item.packing = goods.packing
        item.upNumber = 0
        item.specifications = goods.specifications
      }
      item.edit = false // 初始化为false
    })
    // } else if (goods.tool == 'add') {
    //   console.log('新增数据')
    // }

    // console.log(goodsInfo.value, '修改完之后回显的货物信息数据')
  } else {
    // console.log('不是从货物信息页来的，调接口获取确认详情')
    initConfirmInfo() // 获取确认详情
    // countLongPrice() // 计算长途运费
  }
})

// 获取确认详情接口
async function initConfirmInfo() {
  let params = {
    //  ssoId: orderStore.orderInfo.ssoId
    // ssoId: 42329
    // ssoId: 43191 // 赵思凡下的数据
    // ssoId: 43690 // pc端数据
    // ssoId: 44310 // 赵思凡下的数据
    // ssoId: 44640
    // ssoId: 44829 // 有接货的 有接货费 自提
    ssoId: 45019
  }
  const res = await getList(params)
  // console.log(res.data.rows[0].goodsInfo, '/selfmachine-system/order/list?pageNum')

  if (res.data.code == 200) {
    // 把有的数据都拿出来赋值给表单
    for (const key in formData) {
      if (res.data.rows[0][key]) {
        if (key == 'costList') {
          // formData[key] = Object.assign({}, formData[key], res.data.rows[0][key])
          formData.costList = [...res.data.rows[0].costList]
          console.log(8)
        } else {
          formData[key] = res.data.rows[0][key]
        }
      }
    }
    console.log(res.data.rows[0].costList, 'cost是什么')
    console.log(formData, '获取确认详情后初始化formDataddd')
    console.log(formData.costList, '初始化后的costListddd')

    // 赋值给货物信息，重组一下数据，给每个对象加一个字段edit默认false
    // goodsInfo.value = res.data.rows[0].goodsInfo.map((obj) => {
    //   return { ...obj, edit: false };
    // });
    goodsInfo.value = res.data.rows[0].goodsInfo.map((item) => {
      return {
        goodsName: item.goodsName,
        goodsType: item.goodsType,
        goodsNumber: item.goodsNumber,
        weigh: item.weigh,
        goodsVolume: item.goodsVolume,
        packing: item.packing,
        upNumber: 0,
        specifications: item.specifications,
        edit: false
      }
    })

    // 初始化costListSimple
    if (formData.costList.length != 0) {
      costListSimple.value = res.data.rows[0].costList.map((item) => {
        return {
          actualMoney: item.actualMoney,
          ssopRemark: item.ssopRemark,
          ssopType: item.ssopType
        }
      })
    }
    // 初始化起运地的简单数据
    feeStartSimple.value = res.data.rows[0].costList.filter((item) => {
      if (item.ssopType == '起运地') {
        return {
          ssopRemark: item.ssopRemark,
          actualMoney: item.actualMoney,
          ssopType: item.ssopType
        }
      }
    })
    // 初始化目的地的简单数据
    feeEndSimple.value = res.data.rows[0].costList.filter((item) => {
      if (item.ssopType == '目的地') {
        return {
          ssopRemark: item.ssopRemark,
          actualMoney: item.actualMoney,
          ssopType: item.ssopType
        }
      }
    })

    // 初始化保价
    if (Number(formData.insuredPrice) == 1) {
      insureString.value = `声明价值￥${Number(formData.insuredMoney)}元，费率${Number(formData.insuredRate)}‰，保费￥${Number(formData.insuredFee)}元`
    } else if (Number(formData.insuredPrice) == 0) {
      insureString.value = '不保价'
    }

    // 初始化是否代收货款
    initPaymentToggle()

    // console.log(goodsInfo.value, '重组数据后的goodsInfo')
  } else {
    Taro.showToast({
      title: res.data.msg,
      icon: 'error',
      duration: 2000
    })
  }
}

/* 货物信息增删改start */

// 判断对象里是否有字段为空
function isFieldsEmpty(obj) {
  for (var key in obj) {
    if (key !== 'edit' && obj.hasOwnProperty(key)) {
      if (obj[key] === null || obj[key] === undefined || obj[key] === '') {
        return true
      }
    }
  }
  return false
}

// 添加货物
function toGoodsPage() {
  // 判断是否有个空对象如果有就去编辑，否则不让点添加
  // console.log(goodsInfo.value, '新增的时候判断是否push')
  // 如果最后一个为空就不push
  // console.log(isFieldsEmpty(goodsInfo.value[goodsInfo.value.length - 1]), 'ddd')
  // const emptyFalg = isFieldsEmpty(goodsInfo.value[goodsInfo.value.length - 1])
  // if (emptyFalg) {
  //   Taro.showToast({
  //     title: '请完善货物信息',
  //     icon: 'error',
  //     duration: 2000
  //   })
  //   return
  // }
  // 新增一个空对象，等回来的时候直接当成编辑来做
  const item = {
    goodsName: '',
    goodsType: '',
    goodsNumber: '',
    weigh: '',
    goodsVolume: '',
    packing: '',
    upNumber: '',
    specifications: '',
    edit: true
  }
  goodsInfo.value.push(item)

  // 把表单信息、货物信息存入本地
  confirmStore.order.formData = formData
  confirmStore.order.goodsInfo = goodsInfo.value
  // console.log(goodsInfo.value, '新增加空对象之后的货物信息')
  Taro.navigateTo({
    url: `/pages2/goodsPage/index?goods=${JSON.stringify(item)}`
  })
}

// 编辑货物
function editGoods(item, index) {
  console.log(item, index, '编辑货物')
  // 1.把当前项的edit修改为true
  item.edit = true
  // 2.把表单信息、货物信息存入本地
  confirmStore.order.formData = formData
  // 把其他信息也存到本地
  confirmStore.order.goodsInfo = goodsInfo.value
  // console.log(goodsInfo.value, 'goodsInfo.value是对象还是数组')
  Taro.navigateTo({
    url: `/pages2/goodsPage/index?goods=${JSON.stringify(item)}`
  })
}

// 删除货物
function delGoods(item, index) {
  // 如果只有一条数据不能删除
  if (goodsInfo.value.length !== 1) {
    // 删除这行的数据
    goodsInfo.value.splice(index, 1)
    // console.log(item, index, '删除货物')
  } else {
    Taro.showToast({
      title: '货物信息必填',
      icon: 'error',
      duration: 2000
    })
  }
}

/* 货物信息增删改end */

/* 到达地选点 start */

// 关闭弹窗将子组件数据取出
const closeBranchModel = (obj) => {
  console.log(obj, '子组件传递来的到达地选点')
  showBranchTree.value = false
  if (obj) {
    formData.destinationBranch = obj.destinationBranch
    formData.destinationBranchName = obj.destinationBranchName
    formData.destinationBranchShortName = obj.shortName
  }
}

/* 到达地选点end */

// 关闭库位抽屉组件并接受数据
const closeWareHouse = (msg) => {
  showWareHouse.value = false // 隐藏抽屉组件
  formData.locationName = msg.warehouseName // 接收子组件传递的数据
  // console.log(msg,msg.warehouseName,'子组件传递来的库位信息')
}

// 点击打开选择地址本抽屉组件
const openAddressBook = (writer) => {
  if (writer == '1') {
    formType.value = '发货人'
    addressBookInit.value = {
      name: formData.shipper,
      phone: formData.shipperMobile,
      address: formData.shipperAdd
    }
  } else {
    formType.value = '收货人'
    addressBookInit.value = {
      name: formData.receiver,
      phone: formData.receiverMobile,
      address: formData.receiverAdd
    }
  }
  showAddressForm.value = true
  console.log(addressBookInit.value, 'addressBookInit')
}

// 关闭地址本抽屉组件并接受数据
const closeAddressForm = (msg, user) => {
  showAddressForm.value = false
  console.log(msg, user, '子组件传递的地址簿')
  if (user == '发货人') {
    formData.shipper = msg.name
    formData.shipperMobile = msg.phone
    formData.shipperAdd = msg.address
  } else if (user == '收货人') {
    formData.receiver = msg.name
    formData.receiverMobile = msg.phone
    formData.receiverAdd = msg.address
  }
}

/* 付款方式 start */
// const formData.clearingForm = ref('1') // 付款方式 1现付 2提付 3签单
// 关闭弹窗将子组件数据取出
const closeSignUnitModel = (obj) => {
  console.log(obj, '子组件传递来的签单单位信息')
  showSignUnit.value = false
  if (obj) {
    formData.contractedNo = obj.contractedNo
    formData.customerName = obj.customerName
    billInfo.value = obj.billInfo // 回单要求的详情
    // 根据回单要求详情回显选择的回单类型
    if (obj.billInfo.require == '承运单' || obj.billInfo.require == '签回承运单') {
      billServerGroup.value = ['2']
      formData.billServer = 2
    } else if (obj.billInfo.require == '附单据，资料') {
      billServerGroup.value = ['1']
      formData.billServer = 1
    } else {
      billServerGroup.value = ['3']
      formData.billServer = 3
      formData.billNum = obj.billInfo.require
    }

    // billServerGroup.value = [] //
  }
}
/* 付款方式 end */

/* 接货方式 start */
const receiveStartTimeStr = computed(() => {
  if (!formData.receivingTime) {
    return '请选择接货时间'
  } else {
    // console.log(formData.receivingTime)
    const dateArray = formData.receivingTime.split('&&')
    return dateArray[0] || ''
  }
})

const receiveEndTimeStr = computed(() => {
  if (!formData.receivingTime) {
    return '请选择接货时间'
  } else {
    // console.log(formData.receivingTime)
    const dateArray = formData.receivingTime.split('&&')
    return dateArray[1] || ''
  }
})

// 打开接货时间组件
const openTimeModel = (type) => {
  showReceiveTime.value = true
  timeType.value = Number(type)
}

// 关闭弹窗将子组件数据取出
const closeReceiveTimeModel = (obj) => {
  console.log(obj, '子组件传递来的接货时间信息')
  showReceiveTime.value = false
  timeType.value = ''

  if (obj) {
    const dateArray = formData.receivingTime.split('&&')
    if (obj.timeType == 0) {
      // 拼接上开始时间 赋值给formData
      formData.receivingTime = obj.startTime + '&&' + dateArray[1]
    } else {
      // 拼接上结束时间 赋值给formData
      formData.receivingTime = dateArray[0] + '&&' + obj.endTime
    }
  }
}

/* 接货方式 end */

/* 承运类型 start */
// 关闭弹窗将子组件数据取出
const closeSendTypeModel = (obj) => {
  console.log(obj, '承运类型组件数据')
  showSendType.value = false
  if (obj) {
    // 赋值给formData
    formData.sendType = obj.sendType
    formData.urgent = obj.urgent
  }
}

// 回显承运类型文本
const getSendTypeStr = (sendType) => {
  switch (Number(sendType)) {
    case 1:
      return '快件'
    case 2:
      return '普件'
    case 3:
      return '整车'
    case 4:
      return '506经济件'
    case 5:
      return '506商务件'
    case 6:
      return '次日达'
    case 7:
      return '隔日达'
    default:
      return '请选择承运类型'
  }
}

// 回显是否加急
const getUrgentStr = (urgent) => {
  switch (Number(urgent)) {
    case 0:
      return '不加急'
    case 1:
      return '加急'
    default:
      return '请选择是否加急'
  }
}

/* 承运类型 end */

/* 保价 start */
// 关闭弹窗将子组件数据取出
const closeInsureModel = (obj) => {
  console.log(obj, '保价组件数据')
  showInsure.value = false
  if (obj) {
    // 赋值给formData
    formData.insuredFee = obj.insuredFee
    formData.insuredMoney = obj.insuredMoney
    formData.insuredPrice = obj.insuredPrice
    formData.insuredRate = obj.insuredRate
    if (!obj.insuredPrice) {
      insureString.value = '不保价'
    } else {
      insureString.value = `声明价值￥${Number(obj.insuredMoney)}元，费率${Number(obj.insuredRate)}‰，保费￥${Number(obj.insuredFee)}元`
    }
  }
}
/* 保价 end */

/* 待收货款 start */
// 判断是否能代收货款
async function initPaymentToggle() {
  // console.log(formData.destinationBranch, '是否代收货款的网点编号')
  const res = await getPaymentToggle(formData.destinationBranch)
  // console.log(res.data.data.cannotbeagent, '是否代收货款')
  if (res.data.code == 200) {
    res.data.data.cannotbeagent == 'False' ? collectionPayment.value == true : collectionPayment.value == false
  }
}

// 关闭弹窗将子组件数据取出
const closePaymentModel = (obj) => {
  console.log(obj, '代收货款组件数据')
  showPayment.value = false
  if (obj) {
    paymentStr.value = obj.paymentStr // 代收货款回显文本
    // 赋值给formData
    formData.insuredFee = obj.insuredFee
    formData.insuredMoney = obj.insuredMoney
    formData.insuredPrice = obj.insuredPrice
    formData.insuredRate = obj.insuredRate
  }
}
/* 代收货款 end */

/* 提货方式 start */
// 关闭弹窗将子组件数据取出
const closeDelivereModel = (obj) => {
  console.log(obj, '接收提货方式组件数据')
  showDeliver.value = false
  if (obj) {
    // 赋值给formData
    formData.pickUpMode = obj.pickUpMode // 提货方式
    formData.deliveryType = obj.deliveryType // 送货-送货类型
    formData.dischargeCargo = obj.dischargeCargo // 送货/直送-是否卸货
    formData.dischargeElevator = obj.dischargeElevator // 送货/直送-是否电梯
    formData.dischargeServer = obj.dischargeServer // 送货/直送-卸货-货物类型
    formData.elevatorNum = obj.elevatorNum // 送货/直送-楼层
    formData.subsidyType = obj.subsidyType // 送货/直送-补贴类型
    formData.bonusFee = obj.bonusFee // 送货/直送-补贴费用
    formData.destinationBranch = obj.branchSuggest.branchCompanyNo // 推荐网点编号
    baiduDistance.value = obj.branchSuggest.baiduDistance // 推荐网点数据 距离
    baiduDistanceNo.value = obj.branchSuggest.mileage // 推荐网点数据 不带公里数的距离
    isNormal.value = obj.branchSuggest.isNormal // isNormal用来计算送货费
    formData.urgent = obj.urgent // 是否加急
    formData.limitSend = obj.limitSend // 是否限时送
    formData.goodT = obj.goodT // 货物类型
    formData.largeCargo = obj.goodT.largeCargo // 大件货物
    formData.exhibitionGoods = obj.goodT.exhibitionGoods // 展会货物
    formData.specialGoods = obj.goodT.specialGoods // 特殊货物
    formData.fillingCargo = obj.goodT.fillingCargo // 填仓货物
    formData.holidaySurCharge = obj.goodT.holidaySurCharge // 节假日货物
    // 选中的推荐网点的数据

    let { deliveryType, dischargeCargo, dischargeServer, dischargeElevator, elevatorNum, pickUpMode, subsidyType, bonusFee } = obj

    let sumStr = ''

    if (pickUpMode == '1') {
      sumStr += '自提'
    } else if (pickUpMode == '2') {
      sumStr += '送货'
    } else if (pickUpMode == '3') {
      sumStr += '直送'
    }

    if (deliveryType == '0') {
      sumStr += '(无),'
    } else if (deliveryType == '1') {
      sumStr += '(送商超),'
    } else if (deliveryType == '2') {
      sumStr += '(进仓),'
    } else if (deliveryType == '3') {
      sumStr += '(报关),'
    }

    // 如果补贴
    if (subsidyType == '0') {
      sumStr += '不补贴'
    } else if (subsidyType == '1') {
      sumStr += '补贴类型:二次送货费' + bonusFee + '元'
    } else if (subsidyType == '2') {
      sumStr += '补贴类型:补签单费用' + bonusFee + '元'
    } else if (subsidyType == '3') {
      sumStr += '补贴类型:调增送货费' + bonusFee + '元'
    } else {
      sumStr += '不补贴'
    }

    // 如果卸货
    if (dischargeCargo == '1') {
      if (dischargeServer == '1') {
        sumStr += '卸货服务(标准件)'
      } else if (dischargeServer == '2') {
        sumStr += '卸货服务(非标准件)'
      } else if (dischargeServer == '3') {
        sumStr += '卸货服务(特殊件)'
      }
      // 上楼方式
      if (dischargeElevator == '0') {
        sumStr += '卸货楼层(楼梯'
      } else if (dischargeElevator == '1') {
        sumStr += '卸货楼层(电梯'
      }
      sumStr += elevatorNum + '层)'
    } else {
      sumStr += '不卸货'
    }

    console.log(sumStr, '提货方式文本')
    deliverString.value = sumStr // 提货方式回显文本
  }
}
/* 提货方式 end  */

/* 监听变化 计算 接货费takeFee 长途运费longPrice 送货费sendPrice start */

// 1.1监听规格变化计算总数量 立即监听
watch(
  () => goodsInfo,
  () => {
    const totalNumber = goodsInfo.value.reduce((total, item) => total + Number(item.goodsNumber), 0)
    // console.log(totalNumber, '监听计算总数量')
    totalGoods.value = totalNumber
  },
  { immediate: true, deep: true }
)

// 1.2监听总数量发生变化的时候
watch(
  () => totalGoods,
  (newVal) => {
    console.log(newVal, '总数量新老值')
    //  调接口请求
    // countTakeFee()
  },
  { deep: true }
)

// 2.1监听规格变化计算总体积
watch(
  () => goodsInfo,
  () => {
    const totalVolume = goodsInfo.value.reduce((total, item) => total + Number(item.goodsVolume), 0)
    // console.log(totalVolume, '监听计算体积')
    takeFeeVolume.value = totalVolume
  },
  { deep: true, immediate: true }
)

// 2.2监听总体积发生变化的时候
watch(
  () => takeFeeVolume,
  (newVal) => {
    // console.log(newVal, '总体积新老值')
    //  调接口请求重新计算接货费
    countTakeFee()
    //  调接口请求重新计算长途运费
    countLongPrice()
    // 计算送货费
    countSendPrice()
  },
  { deep: true }
)

// 3.1监听规格变化计算总重量
watch(
  () => goodsInfo,
  () => {
    const totalWeight = goodsInfo.value.reduce((total, item) => total + Number(item.weigh), 0)
    // console.log(totalWeight, '监听计算重量')
    takeFeeWeight.value = totalWeight
  },
  { deep: true }
)

// 3.2监听总重量发生变化的时候
watch(
  () => takeFeeWeight,
  (newVal) => {
    // console.log(newVal, '总重量新老值')
    //  调接口请求重新计算接货费
    countTakeFee()
    //  调接口请求重新计算长途运费
    countLongPrice()
    // 计算送货费
    countSendPrice()
  },
  { deep: true }
)

// 4.1监听承运类型变化
watch(
  () => formData.sendType,
  (newVal) => {
    // console.log(newVal, '承运类型变化')
    //  调接口请求重新计算长途运费
    countLongPrice()
    // 计算送货费
    countSendPrice()
  },
  { deep: true }
)

// 5.1监听目的地网点编号变化
watch(
  () => formData.destinationBranch,
  (newVal) => {
    console.log(newVal, '目的地网点编号/到达地网点编号/推荐网点编号变化')
    //  调接口请求重新计算长途运费
    countLongPrice()
    // 计算送货费
    countSendPrice()
  },
  { deep: true }
)

// 6.1监听目的地地址变化
watch(
  () => formData.destinationAddress,
  (newVal) => {
    console.log(newVal, '目的地网点编号/到达地网点编号/推荐网点编号变化')
    // 计算送货费
    countSendPrice()
  },
  { deep: true, immediate: true }
)

// 7.1监听是否送货
watch(
  () => formData.pickUpMode,
  (newVal) => {
    console.log(newVal, '提货方式')
    if (newVal == '2') {
      // 计算送货费
      countSendPrice()
    }
  },
  { deep: true }
)

// 7.1.1监听送货的时候是否加急
watch(
  () => formData.urgent,
  (newVal) => {
    console.log(newVal, '监听送货的时候是否加急')
    if (formData.pickUpMode == '2') {
      if (newVal !== '0' || !newVal) {
        // 计算送货费
        countSendPrice()
      }
    }
  },
  { deep: true }
)

// 7.1.2监听送货的时候是否限时送
watch(
  () => formData.limitSend,
  (newVal) => {
    console.log(newVal, '监听送货的时候是否限时送')
    if (formData.pickUpMode == '2') {
      if (newVal !== '0' || !newVal) {
        // 计算送货费
        countSendPrice()
      }
    }
  },
  { deep: true }
)

// 8.1监听特殊需求-货物类型-展会货物
watch(
  () => formData.exhibitionGoods,
  (newVal) => {
    console.log(newVal, '监听货物类型变化')
    if (newVal) {
      // 计算长途运费
      countLongPrice()
    }
  },
  { deep: true }
)

// 9.1 监听承运单号给提示
watch(
  () => formData.billNo,
  (newVal) => {
    console.log(newVal, '监听承运单号的程度')
    if (newVal.length !== 9) {
      Taro.showToast({
        icon: 'error',
        title: '请输入9位数'
      })
    }
  },
  { deep: true }
)

// 10.1 监听选中的回单类型 billServerGroup 回单类型选择逻辑+影响附单据费用
watch(
  () => billServerGroup.value,
  (newVal) => {
    console.log(billServerGroup.value, '监听回单类型')
    let checkGroup
    if (newVal) {
      // 计算费用
      // 1.如果付款方式是 签单3
      if (Number(formData.clearingForm) == 3) {
        // 1.回单要求如果不为承运单 就不能手动选按照回单要求billNum回显
        if (Number(formData.billServer) == 3) {
          Taro.showToast({
            icon: 'error',
            title: '不可修改'
          })
          billServerGroup.value = ['3']
          checkGroup = ['3']
        } else if (Number(formData.billServe) == 2) {
          // 2.回单要求如果为承运单 就可以在选择1 但是不能选3 1可取消2必选
          // 判断长度
          if (billServerGroup.value.length == 1) {
            // 不可修改掉2
            billServerGroup.value = ['2']
            checkGroup = ['2']
          } else if (billServerGroup.value.length == 2) {
            // 如果选了2 3提示不可选3
            if (billServerGroup.value.includes('2') && billServerGroup.value.includes('3')) {
              Taro.showToast({
                icon: 'error',
                title: '不可选附厂单'
              })
              // 把数组置为选择2
              billServerGroup.value = ['2']
              checkGroup = ['2']
            }
          }
        }
      } else if (Number(formData.clearingForm) == 1 || Number(formData.clearingForm) == 2) {
        // 2.如果付款方式是 现付1 提付2 最多只能选择两个，且1跟3不能同时存在 叠加金额 附单据5元 承运单5元 附厂单10元
        // 判断长度
        if (billServerGroup.value.length == 1) {
          checkGroup = newVal[0]
        } else if (billServerGroup.value.length == 2) {
          if (billServerGroup.value.includes('1') && billServerGroup.value.includes('3')) {
            Taro.showToast({
              icon: 'error',
              title: '不可以同时选择'
            })
            // 把数组置为选择1
            billServerGroup.value = ['1']
            checkGroup = ['1']
          }
        }
      }
    }
  },
  { deep: true }
)

// 计算接货费
async function countTakeFee() {
  const params = {
    branch: Taro.getStorageSync('btStaff').branchCompanyNo,
    destination: formData.toFromAdd,
    source: formData.startAddress,
    excess: true, // 是否续重
    firs: true, // 是否首重
    numbers: 2,
    orderId: '',
    preorderid: '',
    volume: takeFeeVolume.value,
    weight: takeFeeWeight.value
  }
  const res = await getTakeFee(params)
  if (res.data.code == 200) {
    formData.takeFee = res.data.data
  }
  // console.log(res, '计算接货费')
}

// 计算长途运费 会根据 体积 重量 到达地网点编号 承运类型 货物类型 发生改变而改变
async function countLongPrice() {
  let sendType = Number(formData.sendType)
  let type
  if (sendType == 1) {
    type = '快件'
  } else if (sendType == 2) {
    type = '普件'
  } else if (sendType == 3) {
    type = '整车'
  } else if (sendType == 4) {
    type = '506经济件'
  } else if (sendType == 5) {
    type = '506商务件'
  } else if (sendType == 6) {
    type = '次日达'
  } else if (sendType == 7) {
    type = '隔日达'
  }
  const params = {
    startCompany: Taro.getStorageSync('btStaff').branchCompanyNo, // 起运地网点编号 login里能拿
    desarea: '', // 可以不传
    descCompany: formData.destinationBranch, // 到达地网点编号 目的地网点编号 推荐网点编号 手动选点会变 提货方式选择了推荐网点也会变
    exhibitionGoods: formData.exhibitionGoods, // 是否是展会货物 这个也会变动
    senddate: dayjs(new Date()).format('YYYY-MM-DD'), // 当前时间 2023-10-21
    strarea: '', // 可以不传
    type, //承运类型
    volume: takeFeeVolume.value,
    weight: takeFeeWeight.value
  }
  const res = await getLongPriceFee(params)
  if (res.data.code == 200) {
    // console.log(JSON.parse(res.data.data),'计算长途运费')
    formData.longPrice = JSON.parse(res.data.data).price
  }
}

// 计算送货费 开启送货的时候才有送货费 公里数变化 到达地网点编号 重量 体积 承运类型 大件货物 加急 限时送 发生改变的时候要改变
async function countSendPrice() {
  console.log('计算送货费')
  let sendType = Number(formData.sendType)

  // 是否是大件货物
  let largeCargo
  if (formData.largeCargo == '0' || !formData.largeCargo) {
    largeCargo = false
  } else {
    largeCargo = true
  }
  const params = {
    // mileage: baiduDistance.value, // 公里数
    mileage: baiduDistanceNo.value || 0, // 公里数 不带单位
    // sendTypeSep:, // 根据isNormal来区分
    branch: formData.destinationBranch, // 到达地网点编号 目的地网点编号 推荐网点编号 手动选点会变 提货方式选择了推荐网点也会变
    volume: takeFeeVolume.value,
    weight: takeFeeWeight.value,
    scs: sendType == 1 ? true : false,
    jc: sendType == 2 ? true : false,
    bg: sendType == 3 ? true : false,
    numbers: 1, // 承运单数量
    first: true, // 是否首重
    excess: false, // 是否续重
    djhw: largeCargo, // 大件货物 哪有
    jj: formData.urgent == '0' ? false : true, // 是否加急
    xss: formData.limitSend == '0' ? false : true, // 是否限时送
    special: isNormal.value == '3' ? true : isNormal.value == '1' && baiduDistanceNo.value <= 100 ? true : false, // 特殊货物
    sendTypeSen: sendType == 1 ? true : false // 1 true 其它都 false
  }
  const res = await getSendGoodsFee(params)
  if (res.data.code == 200) {
    console.log(JSON.parse(res.data.data), '计算送货费')
    sendPrice.value = JSON.parse(res.data.data).price || 0 // 送货费
  } else {
    console.log(res.data.msg, '计算送货费')
    // Taro.showToast({
    //   icon: 'error',
    //   title: res.data.msg
    // })
  }
}

/* 监听变化 计算 接货费takeFee 长途运费longPrice 送货费sendPrice end */

/* 其他费用 start */
// 计算 feeStartStr
const feeStartStr = computed(() => {
  let result
  // console.log(feeStartSimple.value,'是完整的吗')
  if (feeStartSimple.value.length != 0) {
    result = feeStartSimple.value.map((item) => `${item.ssopRemark} ${item.actualMoney}元`).join(';')
  } else {
    result = '请填写起运地费用'
  }
  return result
})

// 计算 feeEndStr
const feeEndStr = computed(() => {
  let result
  // console.log(feeEndSimple.value,'是完整的吗')
  if (feeEndSimple.value.length != 0) {
    result = feeEndSimple.value.map((item) => `${item.ssopRemark} ${item.actualMoney}元`).join(';')
  } else {
    result = '请填写目的地费用'
  }
  return result
})

/* 其他费用 end */

/* 起运地其他费用 start */
const closeFeeStartModel = (obj) => {
  console.log(obj, '起运地其他费用信息组件')
  showOtherStart.value = false
  if (obj) {
    feeStartSimple.value = obj.feeStartCostList
  }
}
/* 起运地其他费用 end */

/* 目的地其他费用 start */
const closeFeeEndModel = (obj) => {
  console.log(obj, '目的地其他费用信息组件')
  showOtherEnd.value = false
  if (obj) {
    // 赋值给formData
    feeEndSimple.value = obj.feeEndCostList
  }
}
/* 目的地其他费用 end */

/* 设备信息 start */
// 收货人抽屉
const closePeopleModel = (obj) => {
  console.log(obj, '接收收货人信息组件')
  showPeople.value = false
  if (obj) {
    // 赋值给formData
    formData.receiver = obj.receiver
    formData.receiverMobile = obj.receiverMobile
    receivePeopleStr.value = obj.receiver + obj.receiverMobile
  }
}
/* 设备信息 end */

/* 回单类型 start */

// 计算回单类型文本
const billServerStr = computed(() => {
  if (formData.billServer == 1) {
    return '附单据，资料'
  } else if (formData.billServer == 2) {
    return '承运单'
  } else if (formData.billServer == 3) {
    return '附厂单，资料'
  }
})

/* 回单类型抽屉 start */

// 确定回单类型-编辑
const confirmBillServer = (flag) => {}

/* 回单类型抽屉 end */

/* 接开单员抽屉 start */
// 打开开接单抽屉
const openBillModel = (type) => {
  showBillPeople.value = true
  billType.value = Number(type)
}

const closeBillPeopleModel = (obj) => {
  console.log(obj, '接开单员信息组件')
  showBillPeople.value = false
  if (obj) {
    // 赋值给formData 可能还有别的数据要存
    // formData.STAFF_NO: obj.STAFF_NO
    // formData.ROLE_NAME: obj.ROLE_NAME
    // formData.BTS_NAME:obj.BTS_NAME
    // formData.COMPANY_NAME: obj.COMPANY_NAME
    if (obj.billType == '1') {
      formData.biller = obj.BTS_NAME
    } else {
      formData.taker = obj.BTS_NAME
    }
  }
}
/* 接开单员抽屉 end */

/* 回单类型 end */

/* 厂单日期 start */
const closeFactoryModel = (obj) => {
  console.log(obj, '接收厂单日期组件')
  showFactory.value = false
  if (obj) {
    // 赋值给formData
    formData.factoryDate = obj.factoryDate
  }
}
/* 厂单日期 end */

// 校验身份证号
function validateIDCardNumber(idCardNumber) {
  var pattern = /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|30|31)\d{3}[0-9xX]$/
  if (pattern.test(idCardNumber)) {
    return true // 身份证号格式有效
  } else {
    return false // 身份证号格式无效
  }
}

// 获取表单数据
const submit = () => {
  console.log('获取表单数据', formData)
  console.log('获取货物信息', goodsInfo.value)
  console.log('获取金额')
}
</script>

<style lang="scss">
.confirmbody {
  background: #f5f5f5;
}

.confirmPage {
  .nut-tabs__titles-item.active .nut-tabs__titles-item__line {
    background: var(--nut-tabs-horizontal-tab-line-color, linear-gradient(90deg, var(--nut-primary-color, #0966ff) 0%, rgba(9, 102, 255, 0.15) 100%));
  }
  .nut-cell-group__wrap {
    background: #f5f5f5;
  }

  .nut-cell-group {
    width: 702rpx;
    margin: 0 auto;
  }

  .conCard {
    margin: 10rpx 0;
  }

  .tabCon {
    .dot {
      color: red;
    }

    .fontBlue {
      color: #0966ff;
      background: #f5f5f5;
      // margin-right: 16rpx;
    }

    .fontRed {
      color: #fa5151;
      background: #f5f5f5;
    }

    .nut-cell-group__wrap {
      background: #fff;
    }

    .grayBg {
      width: 650rpx;
      background: #f5f5f5;
      margin: 0 auto;
    }

    .grayInput {
      background: #f5f5f5;
    }

    .nut-input-inner {
      background: #f5f5f5;
    }
  }

  .flex {
    display: flex;
    justify-content: center;
    align-content: center;
  }

  .flex-ld {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fff;
  }

  .flex-end {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    /* 将内容居右对齐 */
  }

  .nut-form-item__body__slots {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .nut-form-item__label {
  }

  .address_del .rows {
    background: #fff;
  }

  .initInput {
    .nut-input {
      border-radius: 8rpx;
      background: #fff;
      margin: 0 24rpx;
      text-align: center;
    }

    .nut-input-inner {
      background: #fff;
      color: #000;
    }

    span {
      width: 100%;
      color: #000;
      font-size: 28rpx;
    }

    .textRight {
      text-align: right;
    }
  }

  .submitBox {
    width: 100%;
    height: 100rpx;
    background: #fff;
    box-sizing: border-box;
    position: fixed;
    bottom: 0rpx;
    left: 50%;
    transform: translateX(-50%);
    z-index: 105;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10rpx;
    .submit {
      width: 200rpx;
      border-radius: 200rpx;
      background: #0966ff;
    }
    .totalFont {
      display: flex;
      justify-content: center;
      align-items: center;

      font-size: 24rpx;
      color: #666;
      span {
        margin: 0 5rpx;
      }
    }
    .blueFont {
      font-size: 40rpx;
      color: #0966ff;
    }
  }

  .feeBox {
    display: flex;
    flex-direction: column;
    margin-bottom: 100rpx;
    text-align: center;
    // height: auto;
    .totalTitle {
      font-size: 24rpx;
      color: #252525;
      margin: 24rpx auto;
    }
    .totalPrice {
      color: #0966ff;
      font-size: 72rpx;
      font-weight: bold;
    }
    .feeLine {
      width: 600rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: #666;
      font-size: 32rpx;
      margin: 16rpx auto;
    }
    .feePopup {
      height: auto;
      background: #000;
    }
  }

  .otherBox {
    .nut-input-box {
      width: 454rpx;
      height: 72rpx;
    }
    .nut-form-item__label {
      width: 230rpx;
    }
    .nut-form-item__body__slots {
      width: 100%;
    }
    .nut-input-box {
      width: 320rpx;
      height: auto;
      padding: 10rpx;
    }
    .nut-input .input-text,
    .nut-input__text--readonly {
    }
    .receivePeople {
      width: 650px;
      padding: 20rpx;
      margin: 0 auto;
      background: #f5f5f5;
    }
    .grayInput {
      background: #f5f5f5;
    }
    span {
      width: 100%;
      color: #000;
      font-size: 28rpx;
      margin-right: 20rpx;
    }
    .span {
      margin-left: 10rpx;
      color: #252525;
    }
    .garyBg {
      padding: 10rpx 20rpx;
    }
  }
}
</style>
